const cloud = require('wx-server-sdk')

cloud.init()

/// (id: PoolId, location: Location) => (StatusCode)
/// StatusCode:

const SUCCESS = 0;
const BAD_ARGUMENT = -1;
const NOT_FOUND = -2;

exports.main = async (event) => {
  const id = event.id;
  const location = event.location;

  if (id == null || location == null) {
    return {
      result: BAD_ARGUMENT
    };
  }

  const db = cloud.database();
  const poolEntry = await db.collection('pool').doc(id).get();

  if (poolEntry == null) {
    return {
      result: NOT_FOUND
    };
  }

  const book = await db.collection('books').doc(poolEntry.book).get();

  if (book == null) {
    return {
      result: NOT_FOUND
    };
  }

  const locationArray = book.location;
  let modified = false;
  let index;

  for (let i = 0; i < locationArray.length; i++) {
    if (locationArray[i].location == location) {
      if (!locationArray[i].present) {
        index = i;
        modified = true;
        break;
      }
    }
  }

  if (!modified) {
    // add new
    await db.collection('books').doc(book._id).update({
      data: {
        location: db.command.push({
          location: location,
          present: true
        })
      }
    })
  } else {
    // modify old
    const key = `location.${index}.present`;
    const query = {};
    query[key] = true;
    await db.collection('books').doc(book._id).update({
      data: query
    });
  }

  await db.collection('pool').doc(id).remove();

  return {
    result: SUCCESS
  };
}
